/*
 * @lc app=leetcode.cn id=99 lang=cpp
 *
 * [99] 恢复二叉搜索树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    vector<int> ans;
    vector<TreeNode *> nodes;

    void dfs(TreeNode *root)
    {
        if (!root)
            return;
        dfs(root->left);
        ans.push_back(root->val);
        nodes.push_back(root);
        dfs(root->right);
    }

    void recoverTree(TreeNode *root)
    {
        if (root == nullptr)
            return;

        dfs(root);

        int l = -1, r = ans.size() - 1;
        for (int i = 1; i < ans.size(); i++)
        {
            if (ans[i] <= ans[i - 1])
            {
                if (-1 == l)
                {
                    l = i - 1;
                    r = i;
                }
                else
                {
                    r = i;
                }
            }
        }
        swap(nodes[l]->val, nodes[r]->val);
    }
};
// @lc code=end
